import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_trtc_cloud/trtc_cloud.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_listener.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_video_view.dart';
import 'package:tencent_trtc_cloud/tx_audio_effect_manager.dart';
import 'package:tencent_trtc_cloud/tx_device_manager.dart';
import 'package:wakelock_for_us/wakelock_for_us.dart';
import 'package:xindong/common/xindong_all.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/extension/extension_string.dart';
import 'package:xindong/manager/xindong_beauty_singleton.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/models/chat_message/xindong_custom_message.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/routes/call/controller/xindong_call_rtc_network_ctr.dart';
import 'package:xindong/routes/call/controller/xindong_call_rtc_volumes_ctr.dart';
import 'package:xindong/routes/call/controller/xindong_call_timer_ctr.dart';
import 'package:xindong/routes/call/dialog/xindong_call_mini_audio_dialog.dart';
import 'package:xindong/routes/call/dialog/xindong_call_mini_video_dialog.dart';
import 'package:xindong/utils/xindong_conversion_util.dart';
import 'package:xindong/utils/xindong_dialog_util.dart';

class XinDongCallRTCController extends GetxController {
  static XinDongCallRTCController get to => Get.find();
  final timerController = Get.put(XinDongCallTimerController(), permanent: true);

  // 房间Id
  String currentRoomId = "";
  String targetUserId = "";

  late XinDongCallRTCVolumesController volumesController;
  late XinDongCallRTCNetworkController networkController;

  // 实时音视频
  late TRTCCloud rtcCloud;
  late TXAudioEffectManager txAudioManager;
  late TXDeviceManager txDeviceManager;

  bool _isInitTRTCCloud = false; // 是否已经初始化，重复会造成多次回调监听
  bool isFrontCamera = true; // 是否使用前置摄像头，默认前置
  bool isHandsFree = true; // 是否免提，默认免提
  bool isMicMute = false; // 是否静音，默认静音
  bool isCameraOff = false; // 是否关闭摄像头
  bool isMineBigVideoWindow = false; //是否我方大视频
  bool targetFirstVideoFrame = false; // 对方首帧视频是否到达
  bool targetVideoAvailable = true; // 对方视频是否可显示

  // 承载视频图像的控件ViewId
  int mineVideoViewId = 0;
  int targetVideoViewId = 0;

  TRTCCloudVideoView get mineVideoView {
    return TRTCCloudVideoView(
      key: const ValueKey("kMineWindow"),
      viewType: TRTCCloudDef.TRTC_VideoView_TextureView,
      onViewCreated: (viewId) async {
        mineVideoViewId = viewId;
        if (isCameraOff) return;
        await rtcCloud.startLocalPreview(isFrontCamera, viewId);
      },
    );
  }

  TRTCCloudVideoView get targetVideoView {
    return TRTCCloudVideoView(
      key: const ValueKey("kTargetWindow"),
      viewType: TRTCCloudDef.TRTC_VideoView_TextureView,
      onViewCreated: (viewId) async {
        targetVideoViewId = viewId;
        await rtcCloud.startRemoteView(targetUserId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, viewId);
      },
    );
  }

  // 判断悬浮窗是否显示对方信息
  bool get isSmallShowTargetVideo {
    if (XinDongCallController.to.status == XinDongCallStatus.minimize) {
      if (isMineBigVideoWindow) {
        // 我的是大窗口，优先显示对方
        // 但是对方没画面，我开摄像头就显示我
        if (!targetVideoAvailable && !isCameraOff) {
          return false;
        }
        return true;
      } else {
        // 优先显示我的
        // 但是对方有画面，我却关了摄像头就显示对方
        if (targetVideoAvailable && isCameraOff) {
          return true;
        }
        return false;
      }
    } else {
      return isMineBigVideoWindow == true;
    }
  }

  //  初始化
  Future<void> init() async {
    _initTRTCCloud();
  }

  // 重置默认值
  void reset() {
    mineVideoViewId = 0;
    targetVideoViewId = 0;
    isHandsFree = true;
    isFrontCamera = true; // 是否使用前置摄像头，默认前置
    isCameraOff = false;
    isMicMute = false;
    isMineBigVideoWindow = false; //是否我方大视频
    targetFirstVideoFrame = false; // 对方首帧视频是否到达
    targetVideoAvailable = true; // 对方视频是否可显示
  }

// 进入房间
  void enterRoom({required dynamic orderId}) async {
    reset();
    final call = XinDongCallController.to;
    // 对方用户ID，字符串
    targetUserId = call.targetUser.uid;
    // 房间ID：发起人UID_订单ID
    if (call.targetVersion == 1) {
      currentRoomId = "${call.inviterID}_$orderId";
    } else {
      currentRoomId = "${call.isMineInvite ? call.mineUser.uid : call.targetUser.uid}_$orderId";
    }
    // 音量
    volumesController = Get.put(XinDongCallRTCVolumesController(), permanent: true);
    // 网络
    networkController = Get.put(XinDongCallRTCNetworkController(), permanent: true);

    // 聊天
    // chatProvider = Provider.of<XinDongCallChatProvider>(navigatorKey.currentContext!, listen: false);
    // chatProvider.clear();

    // 1、聊天(系统公告)
    // final String? notice = "系统提示：通话过程中严禁出现任何涉及色情、淫秽、政治、赌博、暴力等违反国家法律的内容，一经发现我们将立即对账号进行封停处理";
    // final String? notice = serverModel.sysNotice;
    // if (!TextUtil.isEmpty(notice)) {
    //   chatProvider.addToMessageList(chatProvider.noticeModel(notice!));
    // }
    // // 2、免费1分钟
    // if (serverModel.useFreeLive == 0) {
    //   chatProvider.addToMessageList(chatProvider.noticeModel("体验免费视频1分钟"));
    // }

    // 3、余额变更通知（余额不足下一次扣费提醒）
    // XinDongCustomMessage textModel = XinDongCustomMessage();
    // textModel.type = XinDongCustomMessageType.balance;
    // textModel.uid = serverModel.uid;
    // textModel.amount = serverModel.amount;
    // chatProvider.addToMessageList(textModel);
    // XinDongCallControllerProvider.instance.reset();

    _enterTRTCRoom();

    // 记录开始通话时间戳
    // startTimestamp = DateTime.now().millisecondsSinceEpoch;
    // if (XinDongCallProvider.instance.startTimestamp == 0) {
    //   XinDongCallProvider.instance.startTimestamp = serverModel.sysCurrentTime;
    // }
    startConsumerAndTimer(XinDongCallController.to.currentOrderId);
    // 保持屏幕唤醒
    Wakelock.enable();
  }

// 退出房间
  void exitRoom() {
    timerController.destroyTimer();
    _exitTRTCRoom();
    // 关闭屏幕唤醒
    Wakelock.disable();
  }

// 通知开始扣费并开始计时(12200)
  void startConsumerAndTimer(dynamic orderid) {
    if (XinDongCallController.to.currentOrderId == orderid) {
      timerController.countSeconds = 0;
      timerController.createTimer();
    } else {
      print("恶意数据注入");
    }
  }
}

extension XinDongCallIM on XinDongCallRTCController {
  // 添加礼物消息
  // void addGiftMessage(XinDongGroupTextMessage textModel) {
  //   chatProvider.addToMessageList(textModel);
  // }

  void onReceiveNewMessage(V2TimMessage message) {
    if (XinDongCallController.to.status == XinDongCallStatus.active ||
        XinDongCallController.to.status == XinDongCallStatus.minimize) {
      if (message.userID == targetUserId || message.sender == targetUserId) {
        if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM && message.customElem != null) {
          XinDongCustomMessage? model = XinDongConversionUtil.decodeJsonToMessageClass(message.customElem?.data ?? "");

          if (model == null) {
            return;
          }
          if (model.type != null) {
            switch (model.type!) {
            // 通知双方直播正式开始，扣费生效
            // case XinDongCustomMessageType.talkStart:
            //   {
            //     // print(dataMap); //{data: {amount: 99880.0, nextChargeTime: 1678760616317, price: 30, roomId: 10716, sysCurrentTime: 1678760556518, type: 1, uid: 10714}, type: 12200}
            //     XinDongCallServerModel serverModel = XinDongCallServerModel.fromJson(model.data);
            //     startConsumerAndTimer(serverModel);
            //   }
            //   break;
/*
              case XinDongGroupMessageType.receiveGift: //赠送礼物，data:礼物+接收者+发送者
                {
                  Map<String, dynamic> data = model.data;
                  XinDongGroupTextMessage textModel = XinDongGroupTextMessage()
                    ..type = model.type!
                    ..gift = XinDongGiftReceive.fromJson(data);

                  // 如果我是发送者
                  if (message.sender == "${XinDongUserController.to.user.uid}") {
                    textModel.sender = XinDongUserController.to.user;
                    textModel.receiver = XinDongCallProvider.instance.targetUser;
                  } else {
                    textModel.receiver = XinDongUserController.to.user;
                    textModel.sender = XinDongCallProvider.instance.targetUser;
                  }
                  // 无论如何都在聊天页显示
                  addGiftMessage(textModel);
                  try {
                    int? mineUid = XinDongUserController.to.accountUser?.user?.uid;
                    // 动画，只显示我收到的（我赠送的已经显示，如果是我送给我自己，那显示两次也是正常的）
                    if (mineUid == textModel.receiver?.uid) {
                      // XinDongGiftAnimationOverlay.to.addQueue(SVGAModel(
                      //   type: SVGAType.receiveGift,
                      //   name: textModel.gift?.name ?? "",
                      //   svga: textModel.gift?.svga ?? "",
                      //   owner: XinDongUserModel.fromJson(XinDongConversionTool.modelToMap(textModel.sender)),
                      //   target: XinDongUserModel.fromJson(XinDongConversionTool.modelToMap(textModel.receiver)),
                      // ));
                    }
                  } catch (error) {
                    mCatchPrint(error);
                  }
                }
                break;

              case XinDongCustomMessageType.balance: // 用户余额变化
                {
                  XinDongGroupTextMessage textModel = XinDongGroupTextMessage.fromJson(model.data);
                  textModel.type = model.type!;
                  chatProvider.addToMessageList(textModel);
                  // 记录下次扣费时间戳
                  if (textModel.nextChargeTime != null) {
                    XinDongCallProvider.instance.serverModel.nextChargeTime = textModel.nextChargeTime;
                  }
                  // 如果是我的余额变化，则实时改变
                  if (textModel.uid == accountUser.user!.uid && textModel.amount != null) {
                    XinDongUserController.to.updateAmount(textModel.amount!);
                    // 看余额还能扣多少次，聊多少分钟
                    // 还能扣2次，就是还能聊1+2=3分钟的时候，提醒一下用户
                    if (textModel.amount! < (XinDongCallProvider.instance.currentPrice * 3) &&
                        textModel.amount! >= (XinDongCallProvider.instance.currentPrice * 2)) {
                      XinDongGroupTextMessage noticeModel = XinDongGroupTextMessage.fromJson(model.data);
                      noticeModel.type = XinDongGroupMessageType.noticeSystem;
                      noticeModel.text = "通知：您当前余额为${textModel.amount!.toStringAsFixed(2)}金币";
                      chatProvider.addToMessageList(noticeModel);
                    }
                  }
                }
                break;*/
            }
          }
        }
      }
    }
  }

//
// // 回调 - 接收自定义群组消息
// void onReceiveNewGroupMessage(V2TimMessage message) {
//   // 不是当前房间的消息不处理
//   if (message.groupID != roomId.toString()) {
//     return;
//   }
//   if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_CUSTOM && message.customElem != null) {
//     XinDongChatCustomMessage? model = XinDongConversionHelper.decodeJsonToMessageModel(message.customElem!.data!);
//     if (model == null) {
//       return;
//     }
//     XinDongDebugPrint('收到群组消息==== ${model.toString()}');
//     if (model.type != null) {
//       switch (model.type!) {
//         case XinDongGroupMessageType.userChat: // 聊天
//           {
//             XinDongGroupTextMessage textModel = XinDongGroupTextMessage.fromJson(model.data);
//             textModel.type = model.type!;
//             chatProvider.addToMessageList(textModel);
//           }
//           break;
//         case XinDongGroupMessageType.balance: // 用户余额变化
//           {
//             XinDongGroupTextMessage textModel = XinDongGroupTextMessage.fromJson(model.data);
//             textModel.type = model.type!;
//             chatProvider.addToMessageList(textModel);
//             // 记录下次扣费时间戳
//             if (textModel.nextChargeTime != null) {
//               XinDongCallProvider.instance.serverModel.nextChargeTime = textModel.nextChargeTime;
//             }
//             // 如果是我的余额变化，则实时改变
//             if (textModel.uid == accountUser.user!.uid && textModel.amount != null) {
//               XinDongUserController.to.updateAmount(textModel.amount!);
//               // 看余额还能扣多少次，聊多少分钟
//               // 还能扣2次，就是还能聊1+2=3分钟的时候，提醒一下用户
//               if (textModel.amount! < (XinDongCallProvider.instance.currentPrice * 3) &&
//                   textModel.amount! >= (XinDongCallProvider.instance.currentPrice * 2)) {
//                 XinDongGroupTextMessage noticeModel = XinDongGroupTextMessage.fromJson(model.data);
//                 noticeModel.type = XinDongGroupMessageType.noticeSystem;
//                 noticeModel.text = "通知：您当前余额为${textModel.amount!.toStringAsFixed(2)}金币";
//                 chatProvider.addToMessageList(noticeModel);
//               }
//             }
//           }
//           break;
//         case XinDongGroupMessageType.receiveGift: //赠送礼物，data:礼物+接收者+发送者
//           {
//             XinDongGroupTextMessage textModel = XinDongGroupTextMessage.fromJson(model.data);
//             textModel.type = model.type!;
//             // 无论如何都在聊天页显示
//             addGiftMessage(textModel);
//             //   print("zzzzzzzzzzzzaa${textModel.toJson()}");
//             // try {
//             //   // // 飘屏
//             //   // XinDongFloatingScreenOverlay.instance.addQueue(textModel);
//             //   int? mineUid =XinDongUserController.to.accountUser?.user?.uid;
//             //
//             //   // 通话房间通知（只有接收和发送方都匹配才显示）
//             //   if (XinDongCallProvider.instance.status == XinDongCallStatus.active ||
//             //       XinDongCallProvider.instance.status == XinDongCallStatus.minimize) {
//             //     if ((mineUid == textModel.sender?.uid &&
//             //         XinDongCallProvider.instance.targetUser.uid == textModel.receiver?.uid) ||
//             //         (XinDongCallProvider.instance.targetUser.uid == textModel.sender?.uid &&
//             //             mineUid == textModel.receiver?.uid)) {
//             //       // Provider.of<XinDongCallVideoProvider>(navigatorKey.currentContext!, listen: false).addGiftMessage(textModel);
//             //     }
//             //   }
//             //
//             //   // 动画，只显示我收到的（我赠送的已经显示，如果是我送给我自己，那显示两次也是正常的）
//             //   if (mineUid == textModel.receiver?.uid) {
//             //     XinDongGiftAnimationOverlay.to.addQueue(SVGAModel(
//             //       type: SVGAType.receiveGift,
//             //       name: textModel.gift?.name ?? "",
//             //       svga: textModel.gift?.svga ?? "",
//             //       owner: XinDongUserModel.fromJson(XinDongConversionHelper.modelToMap(textModel.sender)),
//             //       target: XinDongUserModel.fromJson(XinDongConversionHelper.modelToMap(textModel.receiver)),
//             //     ));
//             //   }
//             // } catch (error) {
//             //   mCatchPrint(error);
//             // }
//           }
//           break;
//       }
//     }
//   }
// }
}

extension XinDongCallTRTC on XinDongCallRTCController {
  //  初始化
  Future<void> _initTRTCCloud() async {
    mDebugPrint("initTRTC");
    // 创建 TRTCCloud 单例
    rtcCloud = (await TRTCCloud.sharedInstance())!;
    // 获取设备管理模块
    txDeviceManager = rtcCloud.getDeviceManager();
    // 获取音效管理类 TXAudioEffectManager
    txAudioManager = rtcCloud.getAudioEffectManager();
    // 扬声器免提
    txDeviceManager.setAudioRoute(TRTCCloudDef.TRTC_AUDIO_ROUTE_SPEAKER);
    // 前置摄像头
    txDeviceManager.switchCamera(true);
    // 注册事件回调
    rtcCloud.registerListener(onRtcListener);
    // 开启基础美颜
    // TXBeautyManager txBeautyManager = rtcCloud.getBeautyManager();
    // txBeautyManager.setBeautyStyle(TRTCCloudDef.TRTC_BEAUTY_STYLE_NATURE); //beautyStyle美容过滤器风格。0:平滑，1:自然，2:模糊
    // txBeautyManager.setBeautyLevel(9); //beautyLevel美容过滤器的强度。取值范围：0-9；0表示过滤器已禁用，值越大，效果越明显。
    // txBeautyManager.setRuddyLevel(0); //ruddyLevel玫瑰色皮肤过滤器的强度。取值范围：0-9；0表示过滤器已禁用，值越大，效果越明显。
    // txBeautyManager.setWhitenessLevel(9); //增白滤镜的白度等级强度。取值范围：0-9；0表示过滤器已禁用，值越大，效果越明显。
    // txBeautyManager.setFilterStrength(1); //强度值范围：0–1。值越大，效果越明显。默认值：0.5。
    // 视频参数(视频通话只设一次就行了)
    TRTCVideoEncParam encParam = TRTCVideoEncParam();
    encParam.videoResolution = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_1280_720;
    encParam.videoFps = 15;
    encParam.videoBitrate = 1200;
    encParam.videoResolutionMode = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT;
    encParam.enableAdjustRes = true;
    rtcCloud.setVideoEncoderParam(encParam);
    // 设置重力感应的适应模式
    rtcCloud.setGSensorMode(TRTCCloudDef.TRTC_GSENSOR_MODE_DISABLE);
    // 标记已经初始化了
    _isInitTRTCCloud = true;
  }

  // 进TRTC房间
  Future<void> _enterTRTCRoom() async {
    if (_isInitTRTCCloud == false) {
      showToast("TRTC SDK 未初始化");
      return;
    }
    // 美颜特效授权
    XinDongBeautyManager.instance.init();

    // 配置参数
    // 视频和音频都要设置
    rtcCloud.enableAudioVolumeEvaluation(500);
    rtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
    // 是否使用前置摄像头，默认前置
    txDeviceManager.switchCamera(true);
    setHandsFree(true); // 是否免提，默认免提
    setMicMute(false); // 是否静音，默认静音
    // 视频通话显示小窗口
    if (XinDongCallController.to.currentCallType == XinDongCallType.videoCall) {
      setCameraOff(false);
      XinDongCallMiniVideoDialog.instance.show();
    }

    // 进入房间
    await rtcCloud.enterRoom(
      TRTCParams(
        sdkAppId: XinDongAll.instance.isRelease ? kTencentAppID : kTencentAppIDDebug,
        userId: XinDongUserController.to.loginId!,
        userSig: XinDongUserController.to.loginSig!.trimSpaceAndLinefeed,
        strRoomId: currentRoomId,
        streamId: "${XinDongCallController.to.currentOrderId}_${XinDongUserController.to.loginId}",
        role: TRTCCloudDef.TRTCRoleAnchor,
      ),
      XinDongCallController.to.currentCallType == XinDongCallType.audioCall
          ? TRTCCloudDef.TRTC_APP_SCENE_AUDIOCALL
          : TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL,
    );
    // rtcCloud.startPublishing(streamId, streamType);
    return Future.value();
  }

  // 退出TRTC房间
  void _exitTRTCRoom() async {
    try {
      await rtcCloud.stopLocalPreview();
      await rtcCloud.stopLocalAudio();
      await rtcCloud.exitRoom();
    } catch (e) {}
  }

  // 最大化
  Future<void> showFullScreen() async {
    if (XinDongCallController.to.status == XinDongCallStatus.none) return;
    // 页面
    if (XinDongCallController.to.currentCallType == XinDongCallType.videoCall) {
      // 不做处理
      changeVideoView(isMineBigVideoWindow);
    } else if (XinDongCallController.to.currentCallType == XinDongCallType.audioCall) {
      XinDongCallMiniAudioDialog.instance.hide();
    }
    XinDongCallController.to.status = XinDongCallStatus.active;
    XinDongCallController.to.update();
    XinDongCallController.to.pushPage();
  }

  // 最小化
  Future<void> showSmall() async {
    if (XinDongCallController.to.status == XinDongCallStatus.none) return;
    await XinDongCallController.to.exitPage();
    XinDongCallController.to.status = XinDongCallStatus.minimize;
    // 页面
    if (XinDongCallController.to.currentCallType == XinDongCallType.videoCall) {
      XinDongCallMiniVideoDialog.instance.delayedHideButton();
      changeVideoView(isMineBigVideoWindow);
      // if (isMineBigVideoWindow != true) {
      //   changeVideoView(true);
      // }
    } else if (XinDongCallController.to.currentCallType == XinDongCallType.audioCall) {
      XinDongCallMiniAudioDialog.instance.show();
    }
    XinDongCallController.to.update();
  }

  // 闭麦
  Future<void> setMicMute(bool mute) async {
    isMicMute = mute;
    await rtcCloud.muteLocalAudio(mute);
    update();
    return Future.value();
  }

  // 免提
  Future<void> setHandsFree(bool handsFree) async {
    isHandsFree = handsFree;
    if (isHandsFree) {
      await txDeviceManager.setAudioRoute(TRTCCloudDef.TRTC_AUDIO_ROUTE_SPEAKER);
    } else {
      await txDeviceManager.setAudioRoute(TRTCCloudDef.TRTC_AUDIO_ROUTE_EARPIECE);
    }
    update();
    return Future.value();
  }

  // 切换摄像头
  Future<bool> switchCamera() async {
    if (isCameraOff) {
      showToast("摄像头未打开不能切换");
      return false;
    }
    isFrontCamera = !isFrontCamera;
    var result = await txDeviceManager.switchCamera(isFrontCamera);
    update();
    return result == 0;
  }

  // 摄像头
  Future<void> setCameraOff(bool cameraOff) async {
    isCameraOff = cameraOff;
    if (isCameraOff) {
      await rtcCloud.stopLocalPreview();
    } else {
      XinDongBeautyManager.instance.init();
      await rtcCloud.startLocalPreview(isFrontCamera, mineVideoViewId);
    }
    update();
  }

  // 切换画面
  Future<void> changeVideoView(bool mineBigVideo) async {
    isMineBigVideoWindow = mineBigVideo;
    update();
    // 小画面显示本地视频，大画面显示远端视频。
    // if (isMineBigVideoWindow) {
    //   await Future.wait([
    //     // fullWindow全屏控件的viewId挂载本地视频LocalView
    //     rtcCloud.updateLocalView(fullWindowVideoViewId),
    //     // floatingWindow悬浮控件的viewId挂载远端视频RemoteView
    //     rtcCloud.updateRemoteView(
    //       targetUserId,
    //       TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SMALL,
    //       floatingWindowVideoViewId,
    //     ),
    //   ]);
    // } else {
    //   await Future.wait([
    //     // floatingWindow悬浮控件的viewId挂载本地视频LocalView
    //     rtcCloud.updateLocalView(floatingWindowVideoViewId),
    //     // fullWindow全屏控件的viewId挂载远端视频RemoteView
    //     rtcCloud.updateRemoteView(
    //       targetUserId,
    //       TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,
    //       fullWindowVideoViewId,
    //     ),
    //   ]);
    // }
  }

  // 事件回调
  void onRtcListener(TRTCCloudListener type, param) async {
    // XinDongDebugPrint("房间监听 $type $param");
    switch (type) {
      case TRTCCloudListener.onEnterRoom: // 我进入房间
        {
          //result > 0 时为进房耗时（ms），result < 0 时为进房错误码
          if (param > 0) {
            mDebugPrint('进房成功 $currentRoomId');
          } else if (param < 0) {
            mDebugPrint('进房失败 $param');

            // 进入房间失败，5秒后继续重新进入，直至成功
            Future.delayed(const Duration(seconds: 5), () => _enterTRTCRoom());
          }
        }
        break;
      case TRTCCloudListener.onExitRoom: // 我退出了房间
        {
          //reason	离开房间原因，0：主动调用 exitRoom 退房；1：被服务器踢出当前房间；2：当前房间整个被解散。
          if (param >= 0) {
            mDebugPrint('退房成功 $param');
            if (param == 0 && timerController.balanceNotEnough == false) {
              showToast("通话结束");
            } else {
              showToast("${XinDongCallController.to.isConsumer ? "" : "对方"}余额不足，通话结束");
            }
            await XinDongCallController.to.hangup();
          }
        }
        break;
      case TRTCCloudListener.onRemoteUserEnterRoom:
        {
          // userId	用户标识
          // debugPrint("进入房间监听 $type $param");
          // if (XinDongCallController.to.currentCallType == XinDongCallType.videoCall && Platform.isIOS) {
          //   // rtcCloud.startLocalPreview(isFrontCamera, smallVideoViewId);
          //   await rtcCloud.startRemoteView(
          //       targetUserId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG, bigVideoViewId);
          // }
        }
        break;
      case TRTCCloudListener.onRemoteUserLeaveRoom:
        {
          //userId	用户标识 reason	离开原因，0表示用户主动退出房间，1表示用户超时退出，2：被踢出当前房间
          mDebugPrint("退出房间监听 $type $param");
          int reason = param["reason"];
          if (reason == 2 || reason == 0) {
            XinDongCallController.to.hangup();
          } else if (reason == 1) {
            String uid = param["userId"];
            if (uid == targetUserId) {
              await XinDongCallController.to.hangup();
              XinDongDialogUtil.showCallEndDialog();
            }
          }
        }
        break;

      case TRTCCloudListener.onSwitchRole:
        {
          //errCode	错误码，0代表切换成功。切换角色
        }
        break;
      case TRTCCloudListener.onRecvCustomCmdMsg:
        {
          //errCode	错误码，0代表切换成功。切换角色
          mDebugPrint("收到自定义消息 $type $param");
          XinDongCustomMessage? model = XinDongConversionUtil.decodeJsonToMessageClass(param['message']);
          if (model == null) {
            return;
          }
        }
        break;
      case TRTCCloudListener.onMissCustomCmdMsg:
        {
          //errCode	错误码
          // debugPrint("语音房间监听监听 $type $param");
        }
        break;
      case TRTCCloudListener.onUserVoiceVolume: // 音量
        {
          if (XinDongCallController.to.currentCallType != XinDongCallType.audioCall) {
            return;
          }
          // XinDongDebugPrint("音量监听 $type $param"); //{userVolumes: [{userId: 10290, volume: 1}], totalVolume: 0}
          // 重置音量
          volumesController.resetVolumes();
          List userVolumes = param["userVolumes"];
          userVolumes.forEach((volume) {
            String uid = volume["userId"].toString();
            if (uid == "") {
              uid = XinDongCallController.to.mineUser.uid;
            }
            if (uid == volumesController.targetClass.user.uid.toString()) {
              // 对方的音量
              volumesController.targetClass.volume = volume["volume"];
            } else if (uid == volumesController.mineClass.user.uid.toString()) {
              // 我的音量
              volumesController.mineClass.volume = volume["volume"];
            }
          });
          // 更新
          volumesController.notifyUpdate();
        }
        break;
      case TRTCCloudListener.onUserVideoAvailable: // 视频数据可用
        {
          String userId = param['userId'];
          bool available = param['available'] as bool;
          // 根据状态对视频进行开启和关闭
          if (userId == targetUserId) {
            // changeVideoView(true);
            targetVideoAvailable = available;
            update();
          }
        }
        break;
      case TRTCCloudListener.onFirstVideoFrame: // 视频首帧
        {
          try {
            // XinDongDebugPrint('视频首帧 $param');
            // {userId: 10175, streamType: 0, width: 544, height: 960}
            // userId	本地或远程用户 ID，如果 userId == null 代表本地，userId != null 代表远程。
            // streamType	视频流类型：摄像头或屏幕分享。
            // width	画面宽度 height	画面高度
            String? userId = param['userId'];
            if (userId != null && XinDongCallController.to.status == XinDongCallStatus.active) {
              // 根据状态对视频进行开启和关闭
              if (XinDongUserController.to.loginId != userId) {
                if (userId == targetUserId) {
                  targetFirstVideoFrame = true;
                  update();
                }
              }
            }
          } catch (error) {
            mCatchPrint(error);
          }
        }
        break;
      case TRTCCloudListener.onNetworkQuality: // 网络质量
        {
          // TRTCQuality
          // TRTCQuality_Unknown     = 0,     //< 未定义
          // TRTCQuality_Excellent   = 1,     //< 最好
          // TRTCQuality_Good        = 2,     //< 好
          // TRTCQuality_Poor        = 3,     //< 一般
          // TRTCQuality_Bad         = 4,     //< 差
          // TRTCQuality_Vbad        = 5,     //< 很差
          // TRTCQuality_Down        = 6,     //< 不可用
          // localQuality	上行网络质量
          // remoteQuality	下行网络质量
          try {
            // XinDongDebugPrint("网络质量 $type $param");
            List remoteQuality = param['remoteQuality'];
            int local = param['localQuality']["quality"];
            int remote = 0;
            if (remoteQuality.isNotEmpty) {
              remote = remoteQuality.first["quality"];
            }
            networkController.updateWith(local: local, remote: remote);
          } catch (error) {
            mCatchPrint(error);
          }
        }
        break;
      default:
        break;
    }
  }
}
